

package com.carmanagement

import grails.test.mixin.*
import groovy.time.TimeCategory
import spock.lang.Specification

/**
 * See the API for {@link grails.test.mixin.services.ServiceUnitTestMixin} for usage instructions
 */
@TestFor(StatsService)
@Mock( [Vehicle, FullTank] )
class StatsServiceSpec extends Specification {

	def setup() {
	}

	def cleanup() {
	}

	void "test fullTank stats"() {
		given:
		def v = new Vehicle()
		def fullTanks = []
		(0..5).each{
			fullTanks << new FullTank(cost:it, mileage:1, date:new Date() + it, quantity:1, vehicle:v)
		}
		FullTank.metaClass.'static'.findAllByVehicle = {ve -> fullTanks}

		def statsToTest = service.getStatsForFullTank(v)

		expect:
		statsToTest.costsAvg == 2.5
		statsToTest.datesAvg == 1
		statsToTest.mileagesAvg == 1.0
		statsToTest.quantitiesAvg == 1.0
	}

	void "test maintenance stats"() {
		given:
		def v = new Vehicle()
		def maintenances = []
		(0..5).each{
			maintenances << new Maintenance(cost:it, mileage:1, date:new Date() + it, predictedDate: new Date() + (it*2),  vehicle:v)
		}
		Maintenance.metaClass.'static'.findAllByVehicle = {ve -> maintenances}

		when:
		def statsToTest = service.getStatsForMaintenance(v)

		then:
		statsToTest.costsAvg == 2.5
		statsToTest.datesAvg == 1
		statsToTest.mileagesAvg == 1.0
		use( TimeCategory ){

			statsToTest.nextMaintenance.day == 2.days
			statsToTest.nextMaintenance.month == new Date().month
			statsToTest.nextMaintenance.year == new Date().year
		}
	}
}
